package com.cicc.wm.lock;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.core.OrderComparator;

import java.util.Map;
import java.util.Optional;

/**
 * 锁注册工厂
 */
public final class LockRegistryFactory {
    public static LockRegistry getLockRegistry() {
        Map<String, LockRegistry> lockRegistryMap = SpringUtil.getBeansOfType(LockRegistry.class);
        if (lockRegistryMap == null) {
            throw new RuntimeException("Failed to obtain LockRegistry map from Spring context");
        }

        if (CollUtil.isNotEmpty(lockRegistryMap)) {
            Optional<LockRegistry> optionalLockRegistry = lockRegistryMap.values().stream()
                    .sorted(OrderComparator.INSTANCE)
                    .filter(LockRegistry::isActive)
                    .findFirst();
            return optionalLockRegistry.orElseThrow(() -> new RuntimeException("No active LockRegistry found"));
        }

        throw new RuntimeException("No active LockRegistry found");
    }
}
